package test.rocksdb;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.rocksdb.Options;
import org.rocksdb.ReadOptions;
import org.rocksdb.RocksDB;
import org.rocksdb.RocksDBException;
import org.rocksdb.RocksIterator;
import org.rocksdb.WriteBatch;
import org.rocksdb.WriteOptions;
import hyl.core.io.MyFile;

/**
 * 键的存储控制器 封装的是 rocksdb
 * 
 * @author 37798955@qq.com
 *
 */
public class RocksdbMap {

	RocksDB rocksDB;
	

	WriteOptions writeOpts;
	ReadOptions readOptions;
	public WriteOptions getWriteOptions() {
		if (writeOpts == null) {
			writeOpts = new WriteOptions();
			writeOpts.setSync(true);
			writeOpts.setDisableWAL(true);
		}
		return writeOpts;

	}
	public ReadOptions getReadOptions() {
		if (readOptions == null) {
			readOptions = new ReadOptions().setFillCache(false);
		}
		return readOptions;

	}
	public RocksdbMap(Options options, String path) throws IOException, RocksDBException {
		MyFile.openFile(path);
		rocksDB = RocksDB.open(options, path);
		getWriteOptions();
		getReadOptions();

	}

	public String get数据库状态() throws RocksDBException {
		final String str = rocksDB.getProperty("rocksdb.stats");
		return str;
	}

	public void do启动() {
		// 载入配置
	}

	public void put(byte[] key, byte[] value) {
		try {
			rocksDB.put(key, value);
		} catch (RocksDBException e) {
			e.printStackTrace();
			do同步put(key, value);
		}
	}

	public void putMany(Map<byte[], byte[]> 批量数据) throws RocksDBException {
		try (final WriteOptions writeOpt = new WriteOptions()) {
			try (final WriteBatch batch = new WriteBatch()) {
				for (Entry<byte[], byte[]> pp : 批量数据.entrySet()) {
					batch.put(pp.getKey(), pp.getValue());
					rocksDB.write(writeOpt, batch);
				}
			}
		}
	}

	public byte[] get(byte[] key) {
		try {
			return rocksDB.get(key);
		} catch (RocksDBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return do同步get(key);
		}
	}

	public Map<byte[], byte[]> getMany(List<byte[]> keys) {
		try {
			return rocksDB.multiGet(keys);
		} catch (RocksDBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public boolean del(byte[] key) {
		try {
			rocksDB.delete(key);
		} catch (RocksDBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return true;
	}

	public RocksIterator getIterator() {
		return rocksDB.newIterator();
	}

	public void do遍历() {
		RocksIterator iter = rocksDB.newIterator();
		for (iter.seekToFirst(); iter.isValid(); iter.next()) {
			 String key = new String(iter.key());
			 String value = new String(iter.value());
			 System.out.println(key+" ="+value);
		}

	}

	public void do同步put(byte[] key, byte[] value) {

	}

	public byte[] do同步get(byte[] key) {
		return null;
	}

}
